package com.leyou.cart.service;

import com.leyou.cart.client.GoodsClient;
import com.leyou.cart.interceptor.LoginInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.common.pojo.UserInfo;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.pojo.Sku;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private GoodsClient goodsClient;
    private static final String KEY_PREFIX="user:cart:";//区分的前缀
    /**
     * 加入购物车
     * @param cart
     */
    public void addCart(Cart cart) {
        //获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        //查询购物车
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(KEY_PREFIX+userInfo.getId().toString());
        //判断商品是否存在购物车
        String key=cart.getSkuId().toString();
        //获取数量
        Integer num=cart.getNum();
        if(boundHashOps.hasKey(key)){
            //存在更新数量
            String cartJson = boundHashOps.get(key).toString();
            cart = JsonUtils.parse(cartJson, Cart.class);
            cart.setNum(cart.getNum()+num);
            //更新redis中的数量
            boundHashOps.put(key,JsonUtils.serialize(cart));
        }else{
            //不存在新增
            //查询sku
            Sku sku = goodsClient.querySkuBySkuId(cart.getSkuId());
            //设置数据
            cart.setUserId(userInfo.getId());
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setPrice(sku.getPrice());
            cart.setTitle(sku.getTitle());
            cart.setImage(StringUtils.isBlank(sku.getImages())?"":StringUtils.split(sku.getImages(),",")[0]);
            //设置到redis中
            boundHashOps.put(key,JsonUtils.serialize(cart));
        }


    }
    /**
     * 查询购物车
     * @return
     */
    public List<Cart> queryCarts() {
        //获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        //判断用户是否有购物车记录
        if(!redisTemplate.hasKey(KEY_PREFIX+userInfo.getId())){
            return null;
        }
        //获取用户的购物车记录
        BoundHashOperations<String, Object, Object> boundHashOperations = redisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());
        //获得集合的值就是购物车列表
        List<Object> cartsJson = boundHashOperations.values();
        //判断购物车集合是否为空
        if(CollectionUtils.isEmpty(cartsJson)){
            return null;
        }
        //返回序列化后的集合对象
        return cartsJson.stream().map(carts->JsonUtils.parse(carts.toString(),Cart.class)).collect(Collectors.toList());
    }

    /**
     * 修改购物车商品数量
     * @param cart
     */
    public void updateNum(Cart cart) {
        //获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        //判断用户是否有购物车记录
        if(!redisTemplate.hasKey(KEY_PREFIX+userInfo.getId())){
            return;
        }
        //获取用户的购物车记录
        BoundHashOperations<String, Object, Object> boundHashOperations = redisTemplate.boundHashOps(KEY_PREFIX + userInfo.getId());
        //获取数量
        Integer num=cart.getNum();
        //通过skuId获取对应的商品记录
        String cartJson = boundHashOperations.get(cart.getSkuId().toString()).toString();
        //反序列化
        cart=JsonUtils.parse(cartJson,Cart.class);
        //设置Num
        cart.setNum(num);
        //更新
        boundHashOperations.put(cart.getSkuId().toString(),JsonUtils.serialize(cart));
    }

    /**
     * 根据skuId删除购物车商品
     * @param skuId
     */
    public void deleteCart(String skuId) {
        // 获取登录用户
        UserInfo user = LoginInterceptor.getUserInfo();
        //获取redis的key
        String key = KEY_PREFIX + user.getId();
        //通过key查询对应的map
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        //通过skuId删除
        hashOps.delete(skuId);
    }
}
